#include "mainwindow.h"
#include "componentdialog.h"
#include "supplierdialog.h"
#include "componentdetailpage.h" // 用于新的详情页面
#include <QStackedWidget>      // 用于 QStackedWidget
#include <QtSvgWidgets/QSvgWidget> // 用于 SVG 显示控件
#include <QtSvg/QSvgRenderer>    // 用于检查 SVG 有效性
#include <QEvent>                // 用于事件过滤
#include <QMouseEvent>           // 用于鼠标事件
#include "suppliercomponentspage.h" // 用于新的供应商特定元器件页面
// #include <QListWidget> // 不再需要
// #include <QStackedWidget> // 不再需要
// #include <QSplitter> // 不再需要
#include <QHBoxLayout>
#include <QTableWidget>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHeaderView>
#include <QMessageBox>
#include <QDebug>
#include <QTime> // Added for timestamp
#include <QTimer> // Added for delayed checks
#include <QString>
#include <QWidget>
#include <QLineEdit> // 包含 QLineEdit 用于搜索
#include <QLabel>    // 用于标签
#include <QTabWidget> // 用于标签页视图
#include <QSpacerItem> // 用于间距

MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
    setWindowTitle("芯片查询工具");
    resize(1000, 700);

    QWidget* centralWidget = new QWidget(this); //用户界面对象的基类
    setCentralWidget(centralWidget); //设置主窗口的中央控件
    QVBoxLayout* mainAppLayout = new QVBoxLayout(centralWidget); // 为清晰起见重命名 mainVLayout
    mainAppLayout->setSpacing(15);
    mainAppLayout->setContentsMargins(20, 20, 20, 20);

    // 初始化 QStackedWidget 和页面
    mainStackedWidget = new QStackedWidget(this);
    searchPageWidget = new QWidget(this);
    listsPageWidget = new QWidget(this);
    componentDetailPageView = new ComponentDetailPage(this);
    supplierComponentsPageView = new SupplierComponentsPage(this); // 创建供应商元器件页面实例

    // --- 设置搜索页面 (searchPageWidget) ---
    QVBoxLayout* searchPageLayout = new QVBoxLayout(searchPageWidget);
    // searchPageWidget->setLayout(searchPageLayout); // 已由 QVBoxLayout 构造函数设置

    // 顶部搜索区域（重用原始代码）
    QWidget* topSearchWidget = new QWidget();
    QVBoxLayout* topSearchInnerLayout = new QVBoxLayout(topSearchWidget);
    topSearchInnerLayout->setSpacing(10);

    titleLabel = new QLabel("芯片查询工具"); // 将 "Hello" 改回原始标题
    titleLabel->setObjectName("titleLabel");
    titleLabel->setAlignment(Qt::AlignCenter);
    topSearchInnerLayout->addWidget(titleLabel);

    QHBoxLayout* searchBarLayout = new QHBoxLayout();
    mainSearchEdit = new QLineEdit();
    mainSearchEdit->setPlaceholderText("请输入型号/品牌/分类/丝印");
    mainSearchEdit->setObjectName("mainSearchEdit");

    // 设置 QCompleter
    completerModel = new QStringListModel(this);
    searchCompleter = new QCompleter(this);
    searchCompleter->setModel(completerModel);
    searchCompleter->setCaseSensitivity(Qt::CaseInsensitive);
    searchCompleter->setFilterMode(Qt::MatchContains); // 或 Qt::MatchStartsWith
    mainSearchEdit->setCompleter(searchCompleter);

    searchButton = new QPushButton("🔍");
    searchButton->setObjectName("searchButton");
    searchBarLayout->addWidget(mainSearchEdit, 1);
    searchBarLayout->addWidget(searchButton);
    topSearchInnerLayout->addLayout(searchBarLayout);
    
    viewAllListsButton = new QPushButton("查看元器件/供应商列表"); // 新按钮
    viewAllListsButton->setObjectName("viewAllListsButton");
    QHBoxLayout* viewListsButtonLayout = new QHBoxLayout();
    viewListsButtonLayout->addStretch();
    viewListsButtonLayout->addWidget(viewAllListsButton);
    viewListsButtonLayout->addStretch();
    topSearchInnerLayout->addLayout(viewListsButtonLayout); // 将其添加到搜索栏下方

    QHBoxLayout* hotSearchLayout = new QHBoxLayout();
    hotSearchLabel = new QLabel("热搜型号🔥:");
    hotSearchLabel->setObjectName("hotSearchLabel");
    hotSearchLayout->addWidget(hotSearchLabel);
    hotSearchTagsWidget = new QWidget();
    QHBoxLayout* tagsLayout = new QHBoxLayout(hotSearchTagsWidget);
    tagsLayout->setSpacing(10);
    tagsLayout->setContentsMargins(0,0,0,0);
    QStringList hotTags = {"STM32F103C8T6", "ESP32", "ATmega328P", "NRF52832"};
    for (const QString& tagName : hotTags) {
        QPushButton* tagButton = new QPushButton(tagName);
        tagButton->setObjectName("hotSearchTagButton");
        connect(tagButton, &QPushButton::clicked, this, [this, tagName]() {
            this->onHotSearchTagClicked(tagName);
        });
        tagsLayout->addWidget(tagButton);
    }
    tagsLayout->addStretch();
    hotSearchLayout->addWidget(hotSearchTagsWidget, 1);
    topSearchInnerLayout->addLayout(hotSearchLayout);

    searchPageLayout->addWidget(topSearchWidget);

    // 在搜索区域下方添加搜索结果列表控件
    searchResultList = new QListWidget(searchPageWidget); // 父级是 searchPageWidget
    searchResultList->setObjectName("searchResultList");
    searchResultList->setMaximumHeight(150); // 限制高度，根据需要调整
    searchResultList->setFrameShape(QFrame::Box); // 添加边框使其可见
    searchResultList->hide(); // 初始隐藏
    searchPageLayout->addWidget(searchResultList); // 添加到搜索区域下方

    // --- 添加 Logo 到搜索页面布局 ---
    searchPageLayout->addStretch(1); // 在标志上方添加拉伸（比例 1）

    // 创建三个 QSvgWidgets
    infineonLogoWidget = new QSvgWidget(searchPageWidget);
    nxpLogoWidget = new QSvgWidget(searchPageWidget);
    tiLogoWidget = new QSvgWidget(searchPageWidget);

    // 设置对象名称（可选，用于样式/调试）
    infineonLogoWidget->setObjectName("infineonLogoWidget");
    nxpLogoWidget->setObjectName("nxpLogoWidget");
    tiLogoWidget->setObjectName("tiLogoWidget");

    // 加载 SVG 资源
    infineonLogoWidget->load(QStringLiteral(":/logo/infineon"));
    nxpLogoWidget->load(QStringLiteral(":/logo/nxp"));
    tiLogoWidget->load(QStringLiteral(":/logo/ti"));

    // 检查加载（可选，例如其中一个）
    if (!tiLogoWidget->renderer() || !tiLogoWidget->renderer()->isValid()) {
         qWarning("从资源 ':/logo/ti' 加载或渲染 SVG 失败。");
    }
     // 如果需要，为 infineon 和 nxp 添加类似检查

    // 为所有 Logo 设置统一的最大尺寸
    const int maxLogoWidth = 250;
    const int maxLogoHeight = 100;
    infineonLogoWidget->setMaximumSize(maxLogoWidth, maxLogoHeight);
    nxpLogoWidget->setMaximumSize(maxLogoWidth, maxLogoHeight);
    tiLogoWidget->setMaximumSize(maxLogoWidth, maxLogoHeight);
// 安装事件过滤器以检测点击
    infineonLogoWidget->installEventFilter(this);
    nxpLogoWidget->installEventFilter(this);
    tiLogoWidget->installEventFilter(this);

    // 使用 QHBoxLayout 水平排列 Logo 并居中
    QHBoxLayout* logoHLayout = new QHBoxLayout();
    logoHLayout->addStretch(); // 左侧拉伸用于居中
    logoHLayout->addWidget(infineonLogoWidget);
    logoHLayout->addSpacing(20); // 标志之间的间距
    logoHLayout->addWidget(nxpLogoWidget);
    logoHLayout->addSpacing(20); // 标志之间的间距
    logoHLayout->addWidget(tiLogoWidget);
    logoHLayout->addStretch(); // 右侧拉伸用于居中
    
    searchPageLayout->addLayout(logoHLayout); // 将水平布局添加到主垂直布局

    searchPageLayout->addStretch(1); // 在标志下方添加拉伸（比例 1）

    // --- 设置列表页面 (listsPageWidget) ---
    QVBoxLayout* listsPageLayout = new QVBoxLayout(listsPageWidget);

    // 在列表页面顶部添加“返回搜索页”按钮
    backToSearchButton = new QPushButton("返回搜索页");
    backToSearchButton->setObjectName("backToSearchButton");
    QHBoxLayout* backButtonLayout = new QHBoxLayout();
    backButtonLayout->addWidget(backToSearchButton);
    backButtonLayout->addStretch(); // 将按钮对齐到左侧
    listsPageLayout->addLayout(backButtonLayout);
    listsPageLayout->addSpacerItem(new QSpacerItem(20, 10, QSizePolicy::Minimum, QSizePolicy::Fixed)); // 可选间距

    contentTabWidget = new QTabWidget(); // 重新创建或重用现有设置
    contentTabWidget->setObjectName("contentTabWidget");
    // 元器件标签页（从原始构造函数复制并调整）
    QWidget* componentTab = new QWidget();
    QVBoxLayout* componentTabLayout = new QVBoxLayout(componentTab);
    QHBoxLayout* componentButtonsLayout = new QHBoxLayout();
    addComponentBtn = new QPushButton("添加元器件");
    editComponentBtn = new QPushButton("编辑元器件");
    deleteComponentBtn = new QPushButton("删除元器件");
    viewDetailBtn = new QPushButton("查看详情"); // 添加查看详情按钮
    saveComponentsBtn = new QPushButton("保存数据");
    reloadComponentsBtn = new QPushButton("重新加载");
    componentButtonsLayout->addWidget(addComponentBtn);
    componentButtonsLayout->addWidget(editComponentBtn);
    componentButtonsLayout->addWidget(deleteComponentBtn);
    componentButtonsLayout->addWidget(viewDetailBtn); // 将按钮添加到布局
    componentButtonsLayout->addStretch();
    componentButtonsLayout->addWidget(saveComponentsBtn);
    componentButtonsLayout->addWidget(reloadComponentsBtn);
    componentTabLayout->addLayout(componentButtonsLayout);
    componentTable = new QTableWidget(0, 8); // 现在是 8 列
    QStringList componentHeaders = {"ID", "型号", "名称", "封装", "描述", "供应商ID", "库存", "价格"}; // 添加价格列头
    componentTable->setHorizontalHeaderLabels(componentHeaders);
    componentTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    componentTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    componentTable->setSelectionMode(QAbstractItemView::SingleSelection);
    componentTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    componentTable->setObjectName("componentTable");
    componentTable->setSortingEnabled(false); // 禁用排序
    componentTabLayout->addWidget(componentTable);
    contentTabWidget->addTab(componentTab, "元器件管理");

    // 供应商标签页（复制并调整）
    QWidget* supplierTab = new QWidget();
    QVBoxLayout* supplierTabLayout = new QVBoxLayout(supplierTab);
    QHBoxLayout* supplierButtonsLayout = new QHBoxLayout();
    addSupplierBtn = new QPushButton("添加供应商");
    editSupplierBtn = new QPushButton("编辑供应商");
    deleteSupplierBtn = new QPushButton("删除供应商");
    saveSuppliersBtn = new QPushButton("保存数据");
    reloadSuppliersBtn = new QPushButton("重新加载");
    supplierButtonsLayout->addWidget(addSupplierBtn);
    supplierButtonsLayout->addWidget(editSupplierBtn);
    supplierButtonsLayout->addWidget(deleteSupplierBtn);
    supplierButtonsLayout->addStretch();
    supplierButtonsLayout->addWidget(saveSuppliersBtn);
    supplierButtonsLayout->addWidget(reloadSuppliersBtn);
    supplierTabLayout->addLayout(supplierButtonsLayout);
    supplierTable = new QTableWidget(0, 5);
    QStringList supplierHeaders = {"ID", "名称", "联系人", "电话", "地址"};
    supplierTable->setHorizontalHeaderLabels(supplierHeaders);
    supplierTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    supplierTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    supplierTable->setSelectionMode(QAbstractItemView::SingleSelection);
    supplierTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    supplierTable->setObjectName("supplierTable");
    supplierTabLayout->addWidget(supplierTable);
    contentTabWidget->addTab(supplierTab, "供应商管理");
    
    listsPageLayout->addWidget(contentTabWidget, 1); // contentTabWidget 填充 listsPage

    // 将页面添加到 QStackedWidget
    mainStackedWidget->addWidget(searchPageWidget);    // 索引 0
    mainStackedWidget->addWidget(listsPageWidget);     // 索引 1
    mainStackedWidget->addWidget(componentDetailPageView); // 索引 2
    mainStackedWidget->addWidget(supplierComponentsPageView); // 索引 3

    // 将 QStackedWidget 添加到主应用程序布局
    mainAppLayout->addWidget(mainStackedWidget, 1); // 堆叠控件占用大部分空间

    // 加载初始数据（保持不变）
    loadComponentData();
    loadSupplierData();

    // 连接信号和槽
    // 表格及其按钮的原始连接（应仍在 listsPageWidget 中工作）
    connect(addComponentBtn, &QPushButton::clicked, this, &MainWindow::onAddComponent);
    connect(editComponentBtn, &QPushButton::clicked, this, &MainWindow::onEditComponent);
    connect(deleteComponentBtn, &QPushButton::clicked, this, &MainWindow::onDeleteComponent);
    connect(saveComponentsBtn, &QPushButton::clicked, this, &MainWindow::onSaveComponents);
    connect(reloadComponentsBtn, &QPushButton::clicked, this, &MainWindow::onReloadComponents);
    connect(addSupplierBtn, &QPushButton::clicked, this, &MainWindow::onAddSupplier);
    connect(editSupplierBtn, &QPushButton::clicked, this, &MainWindow::onEditSupplier);
    connect(deleteSupplierBtn, &QPushButton::clicked, this, &MainWindow::onDeleteSupplier);
    connect(saveSuppliersBtn, &QPushButton::clicked, this, &MainWindow::onSaveSuppliers);
    connect(reloadSuppliersBtn, &QPushButton::clicked, this, &MainWindow::onReloadSuppliers);
    // 连接新的元器件列表交互
    connect(viewDetailBtn, &QPushButton::clicked, this, &MainWindow::onViewDetailFromList);
    connect(componentTable, &QTableWidget::itemDoubleClicked, this, &MainWindow::onViewDetailFromList);
    
    // 页面导航和搜索的新连接
    // 连接 textChanged 以更新 completer 模型
    connect(mainSearchEdit, &QLineEdit::textChanged, this, &MainWindow::onSearchQueryChanged);
    connect(searchButton, &QPushButton::clicked, this, &MainWindow::onExecuteSearch);
    connect(mainSearchEdit, &QLineEdit::returnPressed, this, &MainWindow::onExecuteSearch); // 按回车键搜索
    connect(viewAllListsButton, &QPushButton::clicked, this, &MainWindow::showListsPage);
    connect(backToSearchButton, &QPushButton::clicked, this, &MainWindow::showSearchPage); // 连接返回按钮
    connect(componentDetailPageView, &ComponentDetailPage::backToMainRequested, this, &MainWindow::showSearchPage);
    // 连接搜索结果列表选择
    connect(searchResultList, &QListWidget::itemClicked, this, &MainWindow::onSearchResultSelected);
    // 连接 SupplierComponentsPage 的信号
    connect(supplierComponentsPageView, &SupplierComponentsPage::backToSearchRequested, this, &MainWindow::showSearchPage);
    connect(supplierComponentsPageView, &SupplierComponentsPage::viewComponentDetailRequested, this, &MainWindow::showComponentDetailById);

    // 设置初始页面
    mainStackedWidget->setCurrentWidget(searchPageWidget);

    // 加载数据后初始填充 completer 模型
    onSearchQueryChanged(""); // 使用空字符串调用以初始填充
    
    // 延迟检查表格内容以诊断问题
    QTimer::singleShot(10, this, &MainWindow::checkTableAfterPopulation);
}

MainWindow::~MainWindow() {
    free_all_components(componentHead);
    free_all_suppliers(supplierHead);
}

// void MainWindow::onNavigationChanged(int index) { // 已移除 - 不再使用
// }

// QWidget* MainWindow::createComponentPage() { // 已移除 - 已集成到构造函数中
// }

// QWidget* MainWindow::createSupplierPage() { // 已移除 - 已集成到构造函数中
// }


// --- 元器件数据处理 ---
void MainWindow::loadComponentData() {
    free_all_components(componentHead); componentHead = nullptr;
    int count = load_components(componentFilename.toUtf8().constData(), &componentHead);
    qDebug() << "从" << componentFilename << "加载了" << count << "个元器件";
    populateComponentTable();
}

void MainWindow::saveComponentData() {
    int count = save_components(componentFilename.toUtf8().constData(), componentHead);
    qDebug() << "将" << count << "个元器件保存到" << componentFilename;
    QMessageBox::information(this, "保存成功", QString("已将 %1 条元器件记录保存到文件。").arg(count));
}

void MainWindow::populateComponentTable(const QString& searchTerm) {
    populateComponentTableCallCount++;
    qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "======= populateComponentTable CALLED (" << populateComponentTableCallCount << ")! SearchTerm: '" << searchTerm << "', componentHead: " << componentHead << " =======";
    if (!componentTable) {
        qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[populateComponentTable] componentTable is null, returning.";
        return;
    }
    qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[populateComponentTable] Before setRowCount(0), current componentTable->rowCount():" << componentTable->rowCount();
    componentTable->setRowCount(0);
    qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[populateComponentTable] After setRowCount(0), componentTable->rowCount():" << componentTable->rowCount();
    int row = 0;
    QString lowerSearchTerm = searchTerm.toLower();
    qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[populateComponentTable] Starting to populate. Search term (lowercase): '" << lowerSearchTerm << "'";

    for (ComponentNode* node = componentHead; node != nullptr; node = node->next) {
        QString modelStr = QString::fromUtf8(node->data.model);
        QString nameStr = QString::fromUtf8(node->data.name);
        QString packageStr = QString::fromUtf8(node->data.package);
        QString descStr = QString::fromUtf8(node->data.description);

        bool matches = false;
        QString matchedField = "N/A";

        if (searchTerm.isEmpty()) {
            matches = true;
            matchedField = "N/A (empty search term)";
        } else {
            if (modelStr.toLower().contains(lowerSearchTerm)) {
                matches = true;
                matchedField = "Model";
            } else if (nameStr.toLower().contains(lowerSearchTerm)) {
                matches = true;
                matchedField = "Name";
            } else if (packageStr.toLower().contains(lowerSearchTerm)) {
                matches = true;
                matchedField = "Package";
            } else if (descStr.toLower().contains(lowerSearchTerm)) {
                matches = true;
                matchedField = "Description";
            }
        }

        if (matches) {
            qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[populateComponentTable] MATCH! ID:" << node->data.id
                     << "Model:" << modelStr << "Matched on:" << matchedField;
            componentTable->insertRow(row);
            QTableWidgetItem* idItem = new QTableWidgetItem();
            idItem->setData(Qt::EditRole, node->data.id);
            componentTable->setItem(row, 0, idItem);

            QTableWidgetItem* modelItem = new QTableWidgetItem(modelStr.isEmpty() ? "N/A" : modelStr);
            componentTable->setItem(row, 1, modelItem);
            // [ITEM_CHECK] for Model
            QTableWidgetItem* currentModelItem = componentTable->item(row, 1);
            if (currentModelItem) {
                qDebug() << "[ITEM_CHECK] Row" << row << "Col 1 Text:" << currentModelItem->text()
                         << "DisplayRole:" << currentModelItem->data(Qt::DisplayRole).toString();
            } else {
                qDebug() << "[ITEM_CHECK_FAIL] Row" << row << "Col 1 item is null!";
            }
            QTableWidgetItem* nameItem = new QTableWidgetItem(nameStr.isEmpty() ? "N/A" : nameStr);
            componentTable->setItem(row, 2, nameItem);
            // [ITEM_CHECK] for Name
            QTableWidgetItem* currentNameItem = componentTable->item(row, 2);
            if (currentNameItem) {
                qDebug() << "[ITEM_CHECK] Row" << row << "Col 2 Text:" << currentNameItem->text()
                         << "DisplayRole:" << currentNameItem->data(Qt::DisplayRole).toString();
            } else {
                qDebug() << "[ITEM_CHECK_FAIL] Row" << row << "Col 2 item is null!";
            }
            QTableWidgetItem* packageItem = new QTableWidgetItem(packageStr.isEmpty() ? "N/A" : packageStr);
            componentTable->setItem(row, 3, packageItem);
            // [ITEM_CHECK] for Package
            QTableWidgetItem* currentPackageItem = componentTable->item(row, 3);
            if (currentPackageItem) {
                qDebug() << "[ITEM_CHECK] Row" << row << "Col 3 Text:" << currentPackageItem->text()
                         << "DisplayRole:" << currentPackageItem->data(Qt::DisplayRole).toString();
            } else {
                qDebug() << "[ITEM_CHECK_FAIL] Row" << row << "Col 3 item is null!";
            }
            QTableWidgetItem* descItem = new QTableWidgetItem(descStr.isEmpty() ? "N/A" : descStr);
            componentTable->setItem(row, 4, descItem);
            // [ITEM_CHECK] for Description
            QTableWidgetItem* currentDescItem = componentTable->item(row, 4);
            if (currentDescItem) {
                qDebug() << "[ITEM_CHECK] Row" << row << "Col 4 Text:" << currentDescItem->text()
                         << "DisplayRole:" << currentDescItem->data(Qt::DisplayRole).toString();
            } else {
                qDebug() << "[ITEM_CHECK_FAIL] Row" << row << "Col 4 item is null!";
            }

            QTableWidgetItem* supplierIdItem = new QTableWidgetItem();
            supplierIdItem->setData(Qt::EditRole, node->data.supplier_id);
            componentTable->setItem(row, 5, supplierIdItem);
            // [ITEM_CHECK] for Supplier ID
            QTableWidgetItem* currentSupplierIdItem = componentTable->item(row, 5);
            if (currentSupplierIdItem) {
                qDebug() << "[ITEM_CHECK] Row" << row << "Col 5 Text:" << currentSupplierIdItem->text()
                         << "DisplayRole:" << currentSupplierIdItem->data(Qt::DisplayRole).toString()
                         << "EditRole:" << currentSupplierIdItem->data(Qt::EditRole).toString();
            } else {
                qDebug() << "[ITEM_CHECK_FAIL] Row" << row << "Col 5 item is null!";
            }

            QTableWidgetItem* quantityItem = new QTableWidgetItem();
            quantityItem->setData(Qt::EditRole, node->data.quantity);
            componentTable->setItem(row, 6, quantityItem);
            // [ITEM_CHECK] for Quantity
            QTableWidgetItem* currentQuantityItem = componentTable->item(row, 6);
            if (currentQuantityItem) {
                qDebug() << "[ITEM_CHECK] Row" << row << "Col 6 Text:" << currentQuantityItem->text()
                         << "DisplayRole:" << currentQuantityItem->data(Qt::DisplayRole).toString()
                         << "EditRole:" << currentQuantityItem->data(Qt::EditRole).toString();
            } else {
                qDebug() << "[ITEM_CHECK_FAIL] Row" << row << "Col 6 item is null!";
            }

            QTableWidgetItem* priceItem = new QTableWidgetItem();
            priceItem->setData(Qt::EditRole, node->data.price);
            componentTable->setItem(row, 7, priceItem);
            // [ITEM_CHECK] for Price
            QTableWidgetItem* currentPriceItem = componentTable->item(row, 7);
            if (currentPriceItem) {
                qDebug() << "[ITEM_CHECK] Row" << row << "Col 7 Text:" << currentPriceItem->text()
                         << "DisplayRole:" << currentPriceItem->data(Qt::DisplayRole).toString()
                         << "EditRole:" << currentPriceItem->data(Qt::EditRole).toString();
            } else {
                qDebug() << "[ITEM_CHECK_FAIL] Row" << row << "Col 7 item is null!";
            }
            row++;
        } else {
            qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[populateComponentTable] SKIP. ID:" << node->data.id
                     << "Model:" << modelStr << "Reason: No match for search term '" << searchTerm << "'";
        }
    }
    qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[populateComponentTable] Finished populating. Total rows added:" << row;
    // 移除实验性重绘代码
    qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[populateComponentTable] populateComponentTable FINISHED. Final componentTable->rowCount():" << componentTable->rowCount();
}

// --- 供应商数据处理 ---
void MainWindow::loadSupplierData() {
    free_all_suppliers(supplierHead); supplierHead = nullptr;
    supplierNameCache.clear(); // 加载前清除缓存
    int count = load_suppliers(supplierFilename.toUtf8().constData(), &supplierHead);
    qDebug() << "从" << supplierFilename << "加载了" << count << "个供应商";
    // 填充缓存
    for (SupplierNode* current = supplierHead; current != nullptr; current = current->next) {
        supplierNameCache.insert(current->data.id, QString::fromUtf8(current->data.name));
    }
    populateSupplierTable(); // 加载和缓存后填充表格
}

void MainWindow::saveSupplierData() {
    int count = save_suppliers(supplierFilename.toUtf8().constData(), supplierHead);
    qDebug() << "将" << count << "个供应商保存到" << supplierFilename;
    QMessageBox::information(this, "保存成功", QString("已将 %1 条供应商记录保存到文件。").arg(count));
}

void MainWindow::populateSupplierTable(const QString& searchTerm) {
    if (!supplierTable) return;
    supplierTable->setRowCount(0);
    int row = 0;
    QString lowerSearchTerm = searchTerm.toLower();
    for (SupplierNode* node = supplierHead; node != nullptr; node = node->next) {
        if (searchTerm.isEmpty() ||
            QString(node->data.name).toLower().contains(lowerSearchTerm) ||
            QString(node->data.contact_person).toLower().contains(lowerSearchTerm) ||
            QString(node->data.phone).toLower().contains(lowerSearchTerm) ||
            QString(node->data.address).toLower().contains(lowerSearchTerm)) {
            supplierTable->insertRow(row);
            supplierTable->setItem(row, 0, new QTableWidgetItem(QString::number(node->data.id)));
            supplierTable->setItem(row, 1, new QTableWidgetItem(node->data.name));
            supplierTable->setItem(row, 2, new QTableWidgetItem(node->data.contact_person));
            supplierTable->setItem(row, 3, new QTableWidgetItem(node->data.phone));
            supplierTable->setItem(row, 4, new QTableWidgetItem(node->data.address));
            row++;
        }
    }
}

// --- 更新搜索 Completer 模型的槽 ---
void MainWindow::onSearchQueryChanged(const QString &query) { // Renamed text to query for clarity
    qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onSearchQueryChanged] CALLED. Query: '" << query << "'. Current componentTable->rowCount():" << (componentTable ? QString::number(componentTable->rowCount()) : "N/A (table null)");
    // 此槽现在仅根据当前数据更新 completer 模型
    // 它不再过滤表格。
    
    QStringList suggestions;
    // 从元器件数据中收集建议（例如，型号和名称）
    for (ComponentNode* node = componentHead; node != nullptr; node = node->next) {
        suggestions << QString::fromUtf8(node->data.model);
        suggestions << QString::fromUtf8(node->data.name);
        // 如果需要，将其他字段添加到建议中（例如，封装、描述片段）
    }
    suggestions.removeDuplicates(); // 移除重复项
    suggestions.sort(Qt::CaseInsensitive); // 可选：排序建议

    if (completerModel) {
        completerModel->setStringList(suggestions);
    }
    
    // 注意：我们此处不根据 'query' 过滤表格。
    // 表格过滤在用户执行搜索时隐式发生 (onExecuteSearch)
    // 或者如果我们稍后重新引入基于 mainSearchEdit 文本的实时表格过滤。
    
    // 原始逻辑（已移除）：
    // int currentTabIndex = contentTabWidget->currentIndex();
    // if (currentTabIndex == 0) { // Component Tab
    //     populateComponentTable(query);
    // } else if (currentTabIndex == 1) { // Supplier Tab
    //     populateSupplierTable(query);
    // }
    qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onSearchQueryChanged] FINISHED. Current componentTable->rowCount():" << (componentTable ? QString::number(componentTable->rowCount()) : "N/A (table null)");
}

// --- 元器件槽 ---（保留现有的槽，例如 onAddComponent 等）
void MainWindow::onAddComponent() {
    ComponentDialog dlg(this, nullptr, true, supplierHead);
    if (dlg.exec() == QDialog::Accepted) {
        if (!add_component(&componentHead, &dlg.data)) {
            QMessageBox::warning(this, "添加失败", "元器件 ID 已存在或内存分配失败。");
        } else {
            qDebug() << "添加了 ID 为" << dlg.data.id << "的元器件";
            populateComponentTable(mainSearchEdit->text()); // 应用当前搜索过滤器
            // 保存数据以确保新添加的供应商也被保存
            saveSupplierData();
        }
    }
}

void MainWindow::onEditComponent() {
    int currentRow = componentTable->currentRow();
    if (currentRow < 0) { QMessageBox::warning(this, "未选择", "请先选择要编辑的元器件。"); return; }
    bool ok; int id = componentTable->item(currentRow, 0)->text().toInt(&ok);
    if (!ok) { QMessageBox::critical(this, "错误", "无法读取所选元器件的 ID。"); return; }
    ComponentNode* nodeToEdit = find_component_by_id(componentHead, id);
    if (!nodeToEdit) { QMessageBox::warning(this, "错误", QString("未找到 ID 为 %1 的元器件。").arg(id)); return; }
    ComponentDialog dlg(this, &nodeToEdit->data, false, supplierHead);
    if (dlg.exec() == QDialog::Accepted) {
        if (update_component(componentHead, &dlg.data)) {
             qDebug() << "更新了 ID 为" << dlg.data.id << "的元器件";
             populateComponentTable(mainSearchEdit->text()); // 应用当前搜索过滤器
             // 保存数据以确保新添加的供应商也被保存
             saveSupplierData();
        } else {
             QMessageBox::warning(this, "更新失败", QString("更新 ID 为 %1 的元器件时发生错误。").arg(dlg.data.id));
        }
    }
}

void MainWindow::onDeleteComponent() {
    int currentRow = componentTable->currentRow();
    if (currentRow < 0) { QMessageBox::warning(this, "未选择", "请先选择要删除的元器件。"); return; }
    bool ok; int id = componentTable->item(currentRow, 0)->text().toInt(&ok);
    if (!ok) { QMessageBox::critical(this, "错误", "无法读取所选元器件的 ID。"); return; }
    if (QMessageBox::question(this, "确认删除", QString("确定要删除 ID 为 %1 的元器件吗？").arg(id), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
        if (!delete_component(&componentHead, id)) {
            QMessageBox::warning(this, "删除失败", QString("未找到或无法删除 ID 为 %1 的元器件。").arg(id));
        } else {
            qDebug() << "删除了 ID 为" << id << "的元器件";
            populateComponentTable(mainSearchEdit->text()); // 应用当前搜索过滤器
        }
    }
}

void MainWindow::onSaveComponents() { saveComponentData(); }
void MainWindow::onReloadComponents() {
    mainSearchEdit->clear(); // 清除搜索字段
    loadComponentData(); // 这将调用 populateComponentTable() 而不带搜索词
}


// --- 供应商槽 ---
void MainWindow::onAddSupplier() {
    SupplierDialog dlg(this);
    if (dlg.exec() == QDialog::Accepted) {
        if (!add_supplier(&supplierHead, &dlg.data)) {
            QMessageBox::warning(this, "添加失败", "供应商 ID 已存在或内存分配失败。");
        } else {
            qDebug() << "添加了 ID 为" << dlg.data.id << "的供应商";
            populateSupplierTable(mainSearchEdit->text()); // 应用当前搜索过滤器
        }
    }
}

void MainWindow::onEditSupplier() {
    int currentRow = supplierTable->currentRow();
    if (currentRow < 0) { QMessageBox::warning(this, "未选择", "请先选择要编辑的供应商。"); return; }
    bool ok; int id = supplierTable->item(currentRow, 0)->text().toInt(&ok);
    if (!ok) { QMessageBox::critical(this, "错误", "无法读取所选供应商的 ID。"); return; }
    SupplierNode* nodeToEdit = find_supplier_by_id(supplierHead, id);
    if (!nodeToEdit) { QMessageBox::warning(this, "错误", QString("未找到 ID 为 %1 的供应商。").arg(id)); return; }
    SupplierDialog dlg(this, &nodeToEdit->data, false);
    if (dlg.exec() == QDialog::Accepted) {
        if (update_supplier(supplierHead, &dlg.data)) {
             qDebug() << "更新了 ID 为" << dlg.data.id << "的供应商";
             populateSupplierTable(mainSearchEdit->text()); // 应用当前搜索过滤器
        } else {
             QMessageBox::warning(this, "更新失败", QString("更新 ID 为 %1 的供应商时发生错误。").arg(dlg.data.id));
        }
    }
}

void MainWindow::onDeleteSupplier() {
    int currentRow = supplierTable->currentRow();
    if (currentRow < 0) { QMessageBox::warning(this, "未选择", "请先选择要删除的供应商。"); return; }
    bool ok; int id = supplierTable->item(currentRow, 0)->text().toInt(&ok);
    if (!ok) { QMessageBox::critical(this, "错误", "无法读取所选供应商的 ID。"); return; }
    if (QMessageBox::question(this, "确认删除", QString("确定要删除 ID 为 %1 的供应商吗？").arg(id), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
        if (!delete_supplier(&supplierHead, id)) {
            QMessageBox::warning(this, "删除失败", QString("未找到或无法删除 ID 为 %1 的供应商。").arg(id));
        } else {
            qDebug() << "删除了 ID 为" << id << "的供应商";
            populateSupplierTable(mainSearchEdit->text()); // 应用当前搜索过滤器
        }
    }
}

void MainWindow::onSaveSuppliers() { saveSupplierData(); }
void MainWindow::onReloadSuppliers() {
    mainSearchEdit->clear(); // 清除搜索字段
    loadSupplierData(); // 这将调用 populateSupplierTable() 而不带搜索词
}

// --- 页面导航和搜索的新槽实现 ---

void MainWindow::onExecuteSearch() {
    qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "======= onExecuteSearch CALLED =======";
    qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] Current mainSearchEdit->text(): '" << (mainSearchEdit ? mainSearchEdit->text() : "N/A (edit null)") << "'";
    qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] Current componentTable->rowCount():" << (componentTable ? QString::number(componentTable->rowCount()) : "N/A (table null)");

    if (searchResultList) {
        qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] Hiding searchResultList.";
        searchResultList->hide(); // 首先隐藏之前的结果
    } else {
        qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] searchResultList is null.";
    }

    QString searchTerm = mainSearchEdit ? mainSearchEdit->text().trimmed() : "";
    qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] Trimmed searchTerm: '" << searchTerm << "'";

    if (searchTerm.isEmpty()) {
        qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] Search term is empty. Returning.";
        // 如果只是清除搜索，可能不显示消息？或者保留它。
        // QMessageBox::information(this, "搜索提示", "请输入搜索关键词。");
        qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] FINISHED (empty search). componentTable->rowCount():" << (componentTable ? QString::number(componentTable->rowCount()) : "N/A (table null)");
        return;
    }

    qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] Executing search for: '" << searchTerm << "'";

    QList<ComponentNode*> matches; // 存储所有匹配项
    qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] Starting search loop over componentHead: " << componentHead;
    // 更灵活的搜索：匹配包含搜索词的型号或名称
    for (ComponentNode* current = componentHead; current != nullptr; current = current->next) {
        QString model = QString::fromUtf8(current->data.model);
        QString name = QString::fromUtf8(current->data.name);
        QString package = QString::fromUtf8(current->data.package); // 获取封装作为字符串
        QString description = QString::fromUtf8(current->data.description); // 获取描述作为字符串
        QString price = QString::number(current->data.price, 'f', 2); // 获取价格作为字符串
        
        bool current_matches = false;
        if (model.contains(searchTerm, Qt::CaseInsensitive)) {
            qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] Match found for ID " << current->data.id << " on Model: " << model;
            current_matches = true;
        } else if (name.contains(searchTerm, Qt::CaseInsensitive)) {
            qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] Match found for ID " << current->data.id << " on Name: " << name;
            current_matches = true;
        } else if (package.contains(searchTerm, Qt::CaseInsensitive)) {
            qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] Match found for ID " << current->data.id << " on Package: " << package;
            current_matches = true;
        } else if (description.contains(searchTerm, Qt::CaseInsensitive)) {
            qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] Match found for ID " << current->data.id << " on Description: " << description;
            current_matches = true;
        } else if (price.contains(searchTerm, Qt::CaseInsensitive)) { // Note: Price search might be broad
            qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] Match found for ID " << current->data.id << " on Price: " << price;
            current_matches = true;
        }

        if (current_matches) {
            matches.append(current);
        }
    }
    qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] Search loop finished. Number of matches:" << matches.size();

    int matchCount = matches.size();

    if (matchCount == 1) {
        qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] Single match found. ID:" << matches.first()->data.id << ". Calling showComponentDetailById.";
        showComponentDetailById(matches.first()->data.id);
    } else if (matchCount > 1) {
        qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] Multiple matches found (" << matchCount << "). Populating searchResultList.";
        if (searchResultList) {
            searchResultList->clear(); // 清除之前的项目
            for (ComponentNode* node : matches) {
                QString displayText = QString("%1 (%2)").arg(QString::fromUtf8(node->data.model)).arg(QString::fromUtf8(node->data.name));
                QListWidgetItem* item = new QListWidgetItem(displayText, searchResultList);
                item->setData(Qt::UserRole, node->data.id); // 在项目数据中存储 ID
                qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] Added to searchResultList: " << displayText << " (ID: " << node->data.id << ")";
            }
            // 调整位置和大小（简单示例，可能需要改进）
            // searchResultList->move(mainSearchEdit->mapToGlobal(QPoint(0, mainSearchEdit->height())));
            searchResultList->adjustSize(); // 根据内容调整大小（可能需要最大高度）
            searchResultList->show();
            searchResultList->setFocus(); // 可选：允许键盘导航
            qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] searchResultList shown and focused.";
        }
    } else {
        qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] No matches found for '" << searchTerm << "'. Showing QMessageBox.";
        QMessageBox::information(this, "搜索结果", QString("未找到与 \"%1\" 相关的元器件。").arg(searchTerm));
    }
    qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << "[onExecuteSearch] FINISHED. componentTable->rowCount():" << (componentTable ? QString::number(componentTable->rowCount()) : "N/A (table null)");
}


// --- 处理搜索结果列表选择的槽 ---
void MainWindow::onSearchResultSelected(QListWidgetItem* item) {
    if (!item) return;

    bool ok;
    int componentId = item->data(Qt::UserRole).toInt(&ok);
    if (ok) {
        searchResultList->hide(); // 选择后隐藏列表
        mainSearchEdit->clearFocus(); // 可选：从搜索编辑框移除焦点
        showComponentDetailById(componentId);
    } else {
        qWarning() << "从选中的搜索结果项获取元器件 ID 失败。";
    }
}

void MainWindow::showComponentDetailById(int componentId) {
    qDebug() << "调用 MainWindow::showComponentDetailById()，ID：" << componentId;
    if (!componentDetailPageView) {
        qWarning() << "componentDetailPageView 为空！无法显示详情。";
        return;
    }
    if (!mainStackedWidget) {
        qWarning() << "mainStackedWidget 为空！无法切换页面。";
        return;
    }

    ComponentNode* node = find_component_by_id(componentHead, componentId);
    if (node) {
        // 从缓存中查找供应商名称
        QString supplierName = supplierNameCache.value(node->data.supplier_id, QString("ID: %1 (未知)").arg(node->data.supplier_id));
        // 注意：这需要 ComponentDetailPage::loadComponentData 接受 supplierName
        componentDetailPageView->loadComponentData(&(node->data), supplierName);
        mainStackedWidget->setCurrentWidget(componentDetailPageView);
    } else {
        QMessageBox::warning(this, "错误", QString("在系统中未找到ID为 %1 的组件数据。").arg(componentId));
        // 可选地，切换回搜索页面
        // showSearchPage();
    }
}


// --- 从元器件列表查看详情的槽 ---
void MainWindow::onViewDetailFromList() {
    if (!componentTable) return;

    int currentRow = componentTable->currentRow();
    if (currentRow < 0) {
        QMessageBox::warning(this, "未选择", "请先在列表中选择要查看详情的元器件。");
        return;
    }

    QTableWidgetItem* idItem = componentTable->item(currentRow, 0); // ID 在第一列（索引 0）
    if (!idItem) {
         QMessageBox::critical(this, "错误", "无法获取所选行的ID单元格。");
         return;
    }

    bool ok;
    int componentId = idItem->text().toInt(&ok);
    if (!ok) {
        QMessageBox::critical(this, "错误", "无法将ID单元格内容转换为有效的整数ID。");
        return;
    }

    showComponentDetailById(componentId);
}


// --- Logo 点击事件过滤器 ---
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    // 检查事件是否为鼠标按键按下
    if (event->type() == QEvent::MouseButtonPress) {
        // 检查哪个 Logo 控件被点击
        int supplierId = -1;
        if (watched == infineonLogoWidget) {
            supplierId = 6; // 假设 Infineon 的 ID 是 6（基于之前的计划）
        } else if (watched == nxpLogoWidget) {
            supplierId = 7; // 假设 NXP 的 ID 是 7
        } else if (watched == tiLogoWidget) {
            supplierId = 5; // 假设 TI 的 ID 是 5
        }

        // 如果点击了我们的 Logo 之一
        if (supplierId != -1) {
            // 将事件转换为 QMouseEvent 以便可能检查按钮等（可选）
            // QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
            // if (mouseEvent->button() == Qt::LeftButton) { ... }
            
            onSupplierLogoClicked(supplierId); // 调用槽函数
            return true; // 事件已处理，停止进一步处理
        }
    }

    // 对于所有其他对象和事件，将其传递给基类
    return QMainWindow::eventFilter(watched, event);
}

// --- 处理 Logo 点击的槽 ---
void MainWindow::onSupplierLogoClicked(int supplierId) {
    qDebug() << "点击了供应商标志！供应商 ID：" << supplierId;

    if (!supplierComponentsPageView) {
        qWarning("supplierComponentsPageView 为空！");
        return;
    }
    if (!mainStackedWidget) {
        qWarning("mainStackedWidget 为空！");
        return;
    }

    QString supplierName = supplierNameCache.value(supplierId, QString("供应商ID: %1").arg(supplierId));
    
    supplierComponentsPageView->loadComponentsForSupplier(supplierId, supplierName, componentHead);
    mainStackedWidget->setCurrentWidget(supplierComponentsPageView);
}

void MainWindow::showSearchPage() {
    qDebug() << "调用了 MainWindow::showSearchPage()";
    if (mainStackedWidget && searchPageWidget) {
        mainStackedWidget->setCurrentWidget(searchPageWidget);
    } else {
        qWarning() << "mainStackedWidget 或 searchPageWidget 为空！无法显示搜索页面。";
    } // showSearchPage 结束
}

void MainWindow::showListsPage() {
    qDebug() << "调用了 MainWindow::showListsPage()";
    if (mainStackedWidget && listsPageWidget) {
        mainStackedWidget->setCurrentWidget(listsPageWidget);
    } else {
        qWarning() << "mainStackedWidget 或 listsPageWidget 为空！无法显示列表页面。";
    }
}

void MainWindow::onHotSearchTagClicked(const QString& searchTerm) {
    qDebug() << "点击了热搜标签：" << searchTerm;
    if (mainSearchEdit) {
        mainSearchEdit->setText(searchTerm);
        onExecuteSearch(); // 直接执行搜索
    }
}

// 重写按键按下事件以处理 Esc 键
void MainWindow::keyPressEvent(QKeyEvent *event) {
    if (event->key() == Qt::Key_Escape) {
        qDebug() << "按下 Esc 键，关闭窗口。";
        close(); // 关闭主窗口
    } else {
        // 调用基类实现处理其他按键
        QMainWindow::keyPressEvent(event);
    }
}

// 延迟检查表格内容的槽函数
void MainWindow::checkTableAfterPopulation() {
    qDebug() << "======= checkTableAfterPopulation (Delayed Check) =======";
    qDebug() << "Current componentTable->rowCount():" << (componentTable ? componentTable->rowCount() : -1);
    
    if (componentTable && componentTable->rowCount() > 0) {
        // 检查第一行 (假设是ID 101)
        QTableWidgetItem* item_0_0 = componentTable->item(0, 0); // ID
        QTableWidgetItem* item_0_1 = componentTable->item(0, 1); // Model
        qDebug() << "Row 0 (ID 101 expected): ID=" << (item_0_0 ? item_0_0->text() : "N/A")
                 << "Model=" << (item_0_1 ? item_0_1->text() : "N/A");

        // 检查最后一行 (假设是ID 702)
        int lastRow = componentTable->rowCount() - 1;
        QTableWidgetItem* item_last_0 = componentTable->item(lastRow, 0); // ID
        QTableWidgetItem* item_last_1 = componentTable->item(lastRow, 1); // Model
        qDebug() << "Row" << lastRow << "(ID 702 expected): ID=" << (item_last_0 ? item_last_0->text() : "N/A")
                 << "Model=" << (item_last_1 ? item_last_1->text() : "N/A");
    } else {
        qDebug() << "No rows in componentTable or table is null!";
    }
    qDebug() << "=======================================================";
}